<template>
	<view style="width: 100%;">
		<!--component/AudioBar.wxml-->
		<view class="audioController2" :style="paddingTB?'margin:'+paddingTB+' auto;':''">
			
			<view class="audioController2-progress" @tap.stop="noneFunc">

				<slider class="audioController2-slider" :value="progress" backgroundColor="#E7E7E7"
					activeColor="#ffffff" block-color="#ffffff" block-size="3" @change="onProgressChanged"
					@changing="onProgressChanging"></slider>
				<view style="display: flex; align-items: center;">
					<view v-if="disable" class="audioController2-btn-play disable">
						<image v-if="isPlaying" class="audioController2-btn-play" :src='STATIC_URL+"805.png"'></image>
						<image v-else class="audioController2-btn-play" :src='STATIC_URL+"806.png"'></image>
					</view>
					<view v-else class="audioController2-btn-play" hover-class="hover-btn" @tap.stop="tapPlayBtn">
						<image v-if="isPlaying" class="audioController2-btn-play" :src='STATIC_URL+"805.png"'></image>
						<image v-else class="audioController2-btn-play" :src='STATIC_URL+"806.png"'></image>
					</view>
					<text class="audioController2-text-1">{{current}}</text>
					<text style="margin: 0 2rpx;">/</text>
					<text v-if="invariantDuration" class="audioController2-text-2">{{invariantDuration}}</text>
					<text v-else
						class="audioController2-text-2">{{duration == '00:00'?(initDuration || '00:00'):duration}}</text>
				</view>
				
			</view>
		</view>
	</view>
</template>

<script>
	// component/AudioBar.js

	/**
	 * @author: lihai
	 * @description: 组件内部控制音频播放
	 * 
	 * 使用这个组件需要依赖：
	 * 1. page页面需要实现方法 AudioBar_getPageAudioInfo 获取当前页面的音频信息
	 * (1) title: 标题
	 * (2) singer: 歌手名
	 * (3) coverImgUrl: 封面图
	 * 
	 */
	import AudioPlayer from "./AudioPlayer.js";
	const CurAudio = AudioPlayer.BgAudioPlayer;
	import Util from "./util.js";
	var INDEX = 0; // AudioBar的序号，多个时候方便调试
	function getDurationText(duration) {
		var minutes = parseInt(duration / 60);

		if (minutes < 10) {
			minutes = '0' + minutes;
		} else {
			minutes = minutes + '';
		}

		var seconds = parseInt(duration % 60 + 0.5);

		if (seconds < 10) {
			seconds = '0' + seconds;
		} else {
			seconds = seconds + '';
		}

		return minutes + ':' + seconds;
	}
	/**
	 * 尝试从音频路径中获取音频的长度
	 * https://xxx.cn/dc217e6f21d203bd20616c52d78d1ebf.durationTime=2232.mp3
	 */
	function getAudioDuration(url) {
		let durationTime = 0;

		if (url) {
			url = decodeURIComponent(url);
			let signStr = "durationTime=";
			let index = url.indexOf(signStr);

			if (index > 0) {
				durationTime = url.substring(index + signStr.length); // console.log(signStr, index, durationTime);
				durationTime = durationTime.split('.')[0];
				durationTime = parseInt(durationTime) / 1000;
			}
		}

		return durationTime;
	}

	export default {
		data() {
			return {
				index: -1,
				//编号，多个音频时用于标识
				current: '00:00',
				duration: '00:00',
				isPlaying: false,
				isEnd: true,
				disable: false,
				progress: "",
				changingTime: "",
				tpl: "",
				tplol: ""
			};
		},

		props: {
			// 音频url
			src: {
				type: String,
				default: ""
			},

			// 初始设置长度
			initDuration: Number,

			// 已知长度 毫秒,这个用于音频长度与实际长度不相等的情况
			invariantDuration: Number,

			paddingTB: {
				type: String,
				default: "0rpx"
			}
		},
		watch: {
			"src": {
				handler: function(src) {
					// todo console.warn('更新src，未实现', src);
					let self = this; // 在 numberA 或者 numberB 被设置时，执行这个函数

					if (!self.initDuration) {
						let duration = getAudioDuration(src);

						if (duration) {
							this.initDuration = duration;
							this.duration = getDurationText(duration);
						}
					} else {
						let time = this.formatTime(self.initDuration);
						this.duration = time;
					}
				},
				immediate: true,
				deep: true
			}
		},
		created() {

		},
		beforeMount: function() {
			if (this.src == null) {
				console.error('注意，attached方法中必须要已经有正确赋值，当前src为null');
			}

			let self = this;
			self.index = ++INDEX;
			// console.log("播放器" + self.index + "开始创建"); // 从当前播放的页面中获取音频信息

			let page = Util.getCurPage();
			let pageAudioInfo = {
				title: "资料音频",
				singer: ""
			};

			if (page.$vm.AudioBar_getPageAudioInfo) {
				/**
				 * title: '',
				  singer: '',
				  coverImgUrl: '',
				  pageLocation: ``,
				  onEndAction: function (info) {},
				  onStartAction: function (info){}
				 */
				pageAudioInfo = page.$vm.AudioBar_getPageAudioInfo();
			}

			pageAudioInfo.src = this.src; // 如果当前播放器有对象，判断是否一样，如果一样，则不新创建

			if (CurAudio.curItem && JSON.stringify(CurAudio.curItem.info) == JSON.stringify(pageAudioInfo)) {
				CurAudio.curItem.componentSelf = self;
				self.innerAudioContext = CurAudio.curItem;
				this.isPlaying = CurAudio.is_play;
				this.isEnd = CurAudio.isEnd;
			} else {
				self.innerAudioContext = {
					index: self.index,
					initDuration: self.initDuration,
					info: pageAudioInfo,
					componentSelf: self,
					onStatusChange: function(status) {
						// console.log("播放器" + this.componentSelf.index + "状态" + status);

						switch (status) {
							case 'ended':
								this.componentSelf.isPlaying = false;
								this.componentSelf.isEnd = true;
								this.componentSelf.onPositionUpdate(0, this.componentSelf
									.innerAudioContext.getDuration());

								if (pageAudioInfo.onEndAction) {
									pageAudioInfo.onEndAction(pageAudioInfo);
								}

								break;

							case 'play':
								// console.log('开始播放');
								this.componentSelf.isPlaying = true;
								this.componentSelf.isEnd = false;

								if (pageAudioInfo.onStartAction) {
									pageAudioInfo.onStartAction(pageAudioInfo);
								}

								break;

							case 'pause':
								this.componentSelf.isPlaying = false;
								break;

							case 'stop':
								this.componentSelf.isPlaying = false;
								this.componentSelf.isEnd = true;
								this.componentSelf.onPositionUpdate(0, this.componentSelf
									.innerAudioContext.getDuration());
								break;
						}
					},
					onTimeUpdate: function(ret) {
						let duration = self.innerAudioContext
							.getDuration(); // 获取不到duration的情况下（微信小程序bug，有可能出现），尝试使用初始设置的长度值

						if (duration == 0 && this.componentSelf.initDuration) {
							duration = this.componentSelf.initDuration;
						} // console.log("onPositionUpdate", ret.currentTime, duration);


						this.componentSelf.onPositionUpdate(ret.currentTime, duration);
					},
					onDisableChange: function(disable) {
						// console.error('!!!!!' + disable);
						this.componentSelf.disable = disable;
					},
					// onPlayEnd: function() {
						
					// 	this.componentSelf.onAudioEnd();
					// }
				};
				CurAudio.attach(self.innerAudioContext);
			}

			if (self.initDuration) {
				self.duration = getDurationText(self.initDuration);
			}
		},
		destroyed: function(e) {
			// this.innerAudioContext.stop();
			// console.log(this.innerAudioContext.onTimeUpdate(function () {}));
			CurAudio.detach(this.innerAudioContext);
		},
		methods: {
			formatTime(seconds) {
			  const mins = Math.floor(seconds / 60);
			  const secs = Math.floor(seconds % 60);
			
			  const formattedMins = mins < 10 ? `0${mins}` : mins;
			  const formattedSecs = secs < 10 ? `0${secs}` : secs;
			
			  return `${formattedMins}:${formattedSecs}`;
			},
			setSource() {},

			/**
			 * 监听 - 播放进度更新
			 */
			onPositionUpdate: function(current, duration) {
				this.$emit('audioDuration', {
					current
				});
				let obj = {
					current: getDurationText(current)
				};

				if (duration) {
					obj.duration = getDurationText(duration);
				}

				if (!this.progressChanging) {
					// console.log(current + ',' + duration + '更新' + ( parseInt(current * 100 / duration)));
					if (this.invariantDuration) {
						obj.progress = parseInt(current * 100 / (this.invariantDuration / 1000));
					} else {
						obj.progress = parseInt(current * 100 / duration);
					}
				}
				this.current = obj.current;
				this.duration = obj.duration;
				this.progress = obj.progress;
				
			},

			/**
			 * 响应 - 播放进度更改
			 */
			onProgressChanged: function(event) {
				let self = this;
				self.progressChanging = false;
				var progress = event.detail.value;
				// console.log('拖动进度条：' + progress * self.innerAudioContext.getDuration() / 100 + ' __ ' + self
				// 	.innerAudioContext.getDuration());
				self.innerAudioContext.seek(progress * self.innerAudioContext.getDuration() / 100);
			},

			/**
			 * 响应 - 播放进度条拖动中
			 */
			onProgressChanging: function(event) {
				let self = this;
				this.changingTime = getDurationText(event.detail.value * self.innerAudioContext.getDuration() / 100);
				this.tpl = event.detail.value * 488 / 100 - 52;
				this.tplol = event.target.offsetLeft;
				this.progressChanging = true;
			},

			/**
			 * 响应 - 点击了播放按钮
			 */
			tapPlayBtn: function(e) {
				let self = this;
				// console.log("点击播放按钮" + self.index + " " + self.isEnd + ' ' + self.isPlaying);
				this.$emit('TapPlayBtn', {
					detail: e
				});

				if (self.isEnd) {
					// self.innerAudioContext.src = this.src;
					self.innerAudioContext.start(self.innerAudioContext.info);
				} else if (self.isPlaying) {
					self.innerAudioContext.pause();
				} else {
					self.innerAudioContext.play();
				}
			},
			noneFunc: function(e) {},
			onAudioEnd() {
				this.$emit('audioEnd');
			},
		}
	};
</script>
<style>
	/* component/AudioBar.wxss */

	.btn-play {
		margin-left: 30rpx;
		width: 20rpx;
		height: 20rpx;
	}

	.btn-play-img {
		width: 20rpx;
		height: 20rpx;
	}

	.hover-btn {
		filter: brightness(0.9);
	}

	/* -------------------------------------- */

	.audioController2 {
		width: 100%;
		/* height: 30rpx; */
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 20rpx;
		border-radius: 10rpx;
		/* background-color: #F7F7F7; */
		color: #fff;
		/* padding-left: 20rpx;
		padding-right: 20rpx; */
		/* padding: 20rpx; */
		/* box-sizing: border-box; */
		/* margin-top: 30rpx;
	  margin-bottom: 30rpx; */
		width: 100%;
		box-sizing: border-box;
	}

	.audioController2-progress {
		position: relative;
		height: 100%;
		flex-shrink: 0;
		flex-grow: 1;
		/* padding-left: 30rpx;
	  padding-right: 30rpx; */
		box-sizing: border-box;
		/* display: flex; */
	}

	.audioController2-slider {
		width: 100%;
		padding: 0;
		margin: 0 !important;
	}

	.audioController2-text-1 {
		font-size: 24rpx;
		/* position: absolute;
		left: 10rpx;
		bottom: 2rpx; */
	}

	.audioController2-text-2 {
		font-size: 24rpx;
		/* position: absolute;
		right: 10rpx;
		bottom: 2rpx; */
	}

	.audioController2-btn-play {
		width: 20rpx;
		height: 20rpx;
		margin-right: 10rpx;
		transform: translateY(-2rpx);
	}

	.disable {
		opacity: 0.5;
	}
</style>